package com.example.jinggai;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONException;
import org.json.JSONObject;

public class FuncActivity extends AppCompatActivity {
    private static MqttClient mqttClient;
    private static MqttConnectOptions mqttConnectOptions;
    Button btn1;
    Button btn2;
    Button btn3;
    Button btn4;
    Button btn5;
    Button btn6;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_func);
        btn1 = findViewById(R.id.btn_1);
        btn2 = findViewById(R.id.btn_2);
        btn3 = findViewById(R.id.btn_3);
        btn4 = findViewById(R.id.btn_4);
        btn5 = findViewById(R.id.btn_5);
//        btn6 = findViewById(R.id.btn_6);

        String user = (String) SPUtils.get(FuncActivity.this,"user","admin");
        if(user.equals("admin")){

            btn4.setEnabled(false);  //管理员不申请

        }else {
            btn5.setEnabled(false);  //用户不审批


        }

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new  Intent(FuncActivity.this,InfoActivity.class);
                startActivity(intent);
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new  Intent(FuncActivity.this,MapActivity.class);
                startActivity(intent);
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new  Intent(FuncActivity.this,BaojingActivity.class);
                startActivity(intent);
            }
        });

        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new  Intent(FuncActivity.this,ChuliActivity.class);
                startActivity(intent);
            }
        });

        btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new  Intent(FuncActivity.this,KaiqiActivity.class);
                startActivity(intent);
            }
        });

//        btn6.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//            }
//        });
        initMqttClient();
    }

    private void createNotificationForNormal(String info) {
        Intent intent = new Intent(this, BaojingActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 100,intent, PendingIntent.FLAG_UPDATE_CURRENT);


        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher)//小图
                .setContentTitle("井盖报警消息")//标题
                .setContentText(info)//内容
                //可选元素
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//大图
                .setWhen(System.currentTimeMillis())//时间
                .setAutoCancel(true)//点击后自动取消
                .setContentIntent(pendingIntent)//点击后执行的意图
                .setTicker("------------")//
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)//设置标识 默认声音/振动/
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))//设置声音，如果需要自定义声音，需要将资源文件复制到存储中
                .setColor(Color.RED)//小图颜色 6.0
                .setNumber(32)//number和附加信息貌似只会显示一个
                .setContentInfo("附加信息")//附加信息
                //.setOnlyAlertOnce(true) 同一个通知 播放首次声音和振动
                .setProgress(100, 20, false);//设置进度 分别为最大进度/实际进度/是否使用动画，如果最后参数为true，签名两个参数无效，最需需要设置setProgress(0,0,false)再取消通知，否则通知取消不了

        NotificationManagerCompat.from(this).notify(1000, builder.build());//分别为 通知的id ， 和通知
    }

    private void initMqttClient() {
        mqttConnectOptions  = new MqttConnectOptions();//MQTT的连接设置
        mqttConnectOptions.setCleanSession(true);//清除连接信息

        mqttConnectOptions.setConnectionTimeout(3);// 设置连接超时时间 单位为秒
        mqttConnectOptions.setKeepAliveInterval(60);//心跳包时间60S
        try { mqttClient = new MqttClient(
                "tcp://114.96.74.180:1883",//连接的地址信息
                "android",//ClientID,使用当前时间戳
                new MemoryPersistence());//
            mqttClient.setCallback(new MqttCallback() {//回调函数
                @Override//连接断开
                public void connectionLost(Throwable throwable) { }
                @Override//接收到消息
                public void messageArrived(String s, MqttMessage mqttMessage)  {
                    Log.e("MqttMsg:", "Topic:"+s+" "+"Msg:"+mqttMessage.toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            String source = mqttMessage.toString();

                            try {
                                JSONObject obj = new JSONObject(source);
                                if(source.contains("Height")){  //高度


                                    JSONObject pa = obj.getJSONObject("params");

                                    if(pa.getInt("Height") < 30){

                                       // height.setText("高度报警"+pa.getInt("Height"));

                                        createNotificationForNormal("高度报警"+pa.getInt("Height"));
                                    }else {

                                        //height.setText("正常"+pa.getInt("Height"));
                                    }


                                }
                                if(source.contains("GasConcentration")){  //气体浓度


                                    JSONObject pa = obj.getJSONObject("params");

                                    if(pa.getInt("GasConcentration") > 30){
                                        createNotificationForNormal("气体浓度报警"+pa.getInt("GasConcentration"));
                                        //nongdu.setText("气体浓度报警"+pa.getInt("GasConcentration"));
                                    }else {

                                       // nongdu.setText("正常"+pa.getInt("GasConcentration"));
                                    }


                                }
                                if(source.contains("Key")){  //角度

                                    JSONObject pa = obj.getJSONObject("params");

                                    if(pa.getInt("Key") > 30){
                                        createNotificationForNormal("角度报警"+pa.getInt("Key"));
                                        //jijaodu.setText("角度报警"+pa.getInt("Key"));
                                    }


                                }


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    });
                }
                @Override//没用过
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { }
            });
            new Thread(new Runnable() {//用任务
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        mqttClient.connect(mqttConnectOptions);
                        if (mqttClient.isConnected()) {
                            Log.e("Mqtt Info", "ConnectSuccess");
                            mqttClient.subscribe("/sys/k0m4uijls9a/demo1/thing/event/property/post",0);//订阅1111,消息等级0
                        }
                    }catch (Exception e){
                        Log.e("Mqtt Err", e.toString());
                    }
                }
            }).start();
        }
        catch (Exception e){
            Log.e("Mqtt Err", e.toString());
        }


    }

}